package com.qianlima.upload.ui.controller;

import com.qianlima.upload.application.FileUploadApp;
import com.qianlima.upload.common.dto.FileCheckReqDto;
import com.qianlima.upload.common.dto.FileDto;
import com.qianlima.upload.common.dto.FileReqDto;
import com.qianlima.upload.common.dto.ResponseDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * @description: 上传文件控制层
 * @author：allms
 * @date: 2023/3/21 14:40
 */
@Api(tags = "文件秒传")
@RestController
@RequestMapping("/")
@AllArgsConstructor
public class UploadController {

    private FileUploadApp fileUploadApp;

    /**
     * 上传文件
     *
     * @return
     */
    @PostMapping("/upload")
    @ApiImplicitParam(name = "file", value = "文件，支持多文件", required = true)
    @ApiOperation(value = "普通文件上传")
    public ResponseDto uploadFile(@RequestParam("file") MultipartFile[] file) {
        if (file.length > 0) {
            return fileUploadApp.upload(Arrays.asList(file));
        }
        return ResponseDto.fail();
    }

    @ApiOperation(value = "分片上传-文件")
    @PostMapping(value = "/fragUploadFile", consumes = "multipart/form-data")
    @ApiImplicitParam(name = "file", value = "分片文件")
    public ResponseDto fragUploadFile(@RequestPart("file") MultipartFile file, FileReqDto reqDto) {
        FileDto fileDto = new FileDto();
        BeanUtils.copyProperties(reqDto, fileDto);
        return fileUploadApp.fragUploadFile(fileDto, file);
    }


    @PostMapping("/check")
    @ApiOperation(value = "分片文件-检查")
    public ResponseDto check(@RequestBody FileCheckReqDto fileCheckReqDto) {
        return fileUploadApp.checkFrag(fileCheckReqDto.getKey(), fileCheckReqDto.getShardTotal());
    }
}
